package boot.spring.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import boot.spring.exception.MathException;
import boot.spring.pagemodel.ActorGrid;
import boot.spring.pagemodel.AjaxResult;
import boot.spring.po.User;
import boot.spring.service.UserService;
import boot.spring.tools.FtpUtil;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    FtpUtil ftpUtil;

    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);



    @RequestMapping(value = "/users", method = RequestMethod.PUT)
    @ResponseBody
    public User updateUser(@RequestBody User u) {
        User user = userService.updateUser(u);
        LOG.info("修改一个用户");
        return user;
    }

    @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    @ResponseBody
    public User getUserById(@PathVariable("id") Integer id) {
        User u = userService.getUserById(id);
        LOG.info("获取一个用户");
        return u;
    }

    @RequestMapping(value = "/users", method = RequestMethod.POST)
    @ResponseBody
    public User add(@RequestBody User u) {
        User user = userService.addUser(u);
        LOG.info("添加一个用户");
        return user;
    }

    @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        userService.deleteUser(id);
        LOG.info("删除一个用户");
        return "success";
    }

    @RequestMapping(value = "/exportuser", method = RequestMethod.POST)
    public void export(HttpServletResponse response) throws IOException {
        List<User> list = userService.getPageUsers(1, 500);
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("用户");
        exportParams.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, User.class, list);
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("user.xlsx", "UTF-8"));
        workbook.write(response.getOutputStream());
    }

    @RequestMapping(value = "/exportTemplateuser", method = RequestMethod.POST)
    public void exportTemplateUser(HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = userService.listUserMap();
        TemplateExportParams params = new TemplateExportParams("static/basetemplate.xlsx", 0);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", list.size());
        map.put("maplist", list);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("user.xlsx", "UTF-8"));
        workbook.write(response.getOutputStream());
    }

    @RequestMapping(value = "/multiExportUser", method = RequestMethod.POST)
    public void multiExportUser(HttpServletResponse response) throws IOException {
        List<Map<String, Object>> sheets = new ArrayList<>();
        List<User> list = userService.getPageUsers(1, 500);
        Map<String, Object> sheet1 = new HashMap<>();
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("用户");
        exportParams.setType(ExcelType.XSSF);
        sheet1.put("title", exportParams);
        sheet1.put("data", list);
        sheet1.put("entity", User.class);

        sheets.add(sheet1);
        Workbook workbook = ExcelExportUtil.exportExcel(sheets, ExcelType.XSSF);
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=multiexportuser.xlsx");
        workbook.write(response.getOutputStream());
    }

    @RequestMapping(value = "/importuser", method = RequestMethod.POST)
    @ResponseBody
    public void importExcel(@RequestParam MultipartFile uploadfile) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        List<User> list = ExcelImportUtil.importExcel(uploadfile.getInputStream(), User.class, params);
        list.forEach(u -> System.out.println(u));
    }

    @RequestMapping(value = "/showuser", method = RequestMethod.GET)
    String showUser() {
        return "showuser";
    }

    @RequestMapping(value = "/downloadFTPUser", method = RequestMethod.GET)
    @ResponseBody
    public void downloadFTPUser() throws Exception {
        ftpUtil.downloadFiles("/wsz", "/测试1dd.png", "D://pic");
    }

    @RequestMapping(value = "/exportFTPUser", method = RequestMethod.GET)
    @ResponseBody
    public void exportFTPUser(HttpServletResponse response) throws Exception {
        InputStream is = ftpUtil.exportFile("/王", "/测试1.png");
        response.setContentType("application/x-png");
        response.setHeader("Content-Disposition", "attachment;filename=1.png");
        ServletOutputStream output = response.getOutputStream();
        IOUtils.copy(is, output);
    }

    @RequestMapping(value = "/exportBase64User", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult exportBase64User(HttpServletResponse response) throws Exception {
        String base64 = ftpUtil.exportBase64("/王", "/测试1.png");
        return AjaxResult.success(base64);
    }

    @RequestMapping(value = "/exceptionUser/{id}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult exceptionUser(@PathVariable Integer id) throws MathException {
        if (id == 1) {
            throw new RuntimeException("运行错误");
        } else {
            throw new MathException("计算错误");
        }
    }

    @RequestMapping(value = "/groupuser", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, List<User>> groupUser() {
        List<User> list = userService.getPageUsers(1, 888);
        Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getRegistrationDate));
        collect.forEach((a, b) -> {
            System.out.println(a + ": " + b.stream().mapToInt(User::getUserId).count());
        });
        return collect;
    }


}